package com.A21MobileSales;

import java.io.IOException;
import java.math.BigInteger;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.A21.Object.Global;
import com.A21.Object.MSTSettings;
import com.A21.Object.MSTUser;
import com.A21MobileSales.DataBase.DatabaseHelper;
import com.A21MobileSales.DataBase.MyClass;
import com.A21MobileSales.JsonServices.Download;

public class LoginActivity extends Activity {

	private static final int RESULT_SETTINGS = 1;
	// TextView txtIMEI;
	EditText edtUsername, edtPassword;
	Button btnLogIn, btnSetting, btnSync;
	// ImageView imgLogo;
	Connection cd3;
	Boolean isInternetPresent3 = false;
	AlertDialog.Builder _Alert;

	LinearLayout lnUserName, lnPassword, lnBtn;
	Animation slideUp, slideDown;
	int timeDelay = 2000;

	void initDB() {
		DatabaseHelper myDbHelper = new DatabaseHelper(LoginActivity.this);
		try {

			myDbHelper.createDataBase();
			myDbHelper.openDataBase();

		} catch (IOException ioe) {

			throw new Error("Unable to create database");

		}

		slideUp = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_up);
		slideDown = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_down);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initDB();

		setContentView(R.layout.login_main);

		try {
			lnUserName = (LinearLayout) findViewById(R.id.lnUserName);
			lnPassword = (LinearLayout) findViewById(R.id.lnPassword);
			lnBtn = (LinearLayout) findViewById(R.id.lnBtn);

			// txtIMEI = (TextView) findViewById(R.id.LS_txtIMEI);
			edtUsername = (EditText) findViewById(R.id.Ls_edtusername);
			edtPassword = (EditText) findViewById(R.id.LS_edtpassword);
			btnLogIn = (Button) findViewById(R.id.LS_btnLogin);
			// imgLogo = (ImageView) findViewById(R.id.imgLogo);
			// DatabaseHelper myDbHelper = new
			// DatabaseHelper(LoginActivity.this);
			// try {
			// byte[] bteLogo = myDbHelper.getImageLogo("SystemLogo");
			// if (bteLogo != null) {
			// Bitmap bitmap = BitmapFactory.decodeByteArray(bteLogo, 0,
			// bteLogo.length);
			// Drawable drawable = new BitmapDrawable(getResources(),
			// bitmap);
			// imgLogo.setImageDrawable(drawable);
			// }
			// } catch (Exception e) {
			// // TODO: handle exception
			// }

			btnLogIn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					DoLogin();
				}
			});

			// Button for Setting.
			btnSetting = (Button) findViewById(R.id.LS_btnSetting);
			btnSetting.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!edtUsername.getText().toString().equals("admin")) {
						AlertDialog("Invalid username.");
						return;
					}

					if (!edtPassword.getText().toString().equals("a2000@amk")) {
						AlertDialog("Invalid password.");
						return;
					}
					FunBtnSetting();
				}
			});

			// Button for Setting.
			btnSync = (Button) findViewById(R.id.LS_btnSync);
			btnSync.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!MyClass.getSettingstrDownlaodurl().equals("0")
							&& !edtUsername.getText().toString().isEmpty()) {
						FunBtnSync();
					} else {
						Toast.makeText(LoginActivity.this,
								"Please enter Username and Password.",
								Toast.LENGTH_LONG).show();
					}

				}
			});
			MyClass.setSettingstrDownloadurl(GetPrefSettingsByKey("prefURLDL"));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		loadItemContent();
	}

	void loadItemContent() {
		new Handler().postDelayed(new Runnable() {
			public void run() {
				if (lnUserName.getVisibility() == View.INVISIBLE) {

					lnUserName.startAnimation(slideUp);
					lnUserName.setVisibility(View.VISIBLE);
				}
				if (lnPassword.getVisibility() == View.INVISIBLE) {

					lnPassword.startAnimation(slideUp);
					lnPassword.setVisibility(View.VISIBLE);
				}
				if (btnLogIn.getVisibility() == View.INVISIBLE) {

					btnLogIn.startAnimation(slideUp);
					btnLogIn.setVisibility(View.VISIBLE);
				}
				if (lnBtn.getVisibility() == View.INVISIBLE) {

					lnBtn.startAnimation(slideUp);
					lnBtn.setVisibility(View.VISIBLE);
				}
			}
		}, timeDelay);
	}

	@Override
	public void onStart() {
		super.onStart();

		try {
			// Get Device IMEI Number.
			// TelephonyManager telephonyManager = (TelephonyManager)
			// LoginActivity.this
			// .getSystemService(Context.TELEPHONY_SERVICE);
			// String IMEI_Number = telephonyManager.getDeviceId();
			//
			// if (IMEI_Number == null) {
			// IMEI_Number = Build.SERIAL;
			// }
			//
			// txtIMEI.setText("IMEI / SN : " + IMEI_Number);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	// Function for login button click event
	public void DoLogin() {
		try {
			String strMessage = "Please enter the username.";
			// TODO Auto-generated method stub
			if (!edtUsername.getText().toString().isEmpty()) {
				DatabaseHelper myDbHelper = new DatabaseHelper(
						LoginActivity.this);
				String pwd = edtPassword.getText().toString();
				int password = 0;
				for (int i = 1; i <= pwd.length(); i++) {
					String strChar = pwd.substring(i - 1, i).toString();
					char character = strChar.charAt(0);
					int asc_num = CharToASCII(character);
					BigInteger pwInt = BigInteger.valueOf(i).pow(3);
					password += (asc_num - pwd.length() + i) * pwInt.intValue();
				}
				MSTUser User = myDbHelper.CheckUserNameAndPassWord(edtUsername
						.getText().toString(), Integer.toString(password));
				if (User != null) {
					User.strPassword = pwd;
					Global.setLoggedInUser(User);
					Intent intent = new Intent(LoginActivity.this,
							HomeScreen.class);
					MSTSettings setting = myDbHelper.GetSystemSettingsById("1");
					Global.setMSTSettings(setting);
					startActivity(intent);
					this.finish();
				} else {
					AlertDialog("Invalid username or password.");
				}
			} else {
				AlertDialog(strMessage);
			}
		} catch (Exception ex) {
			Toast.makeText(LoginActivity.this, ex.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	// Function for button Setting
	public void FunBtnSetting() {
		try {
			// Navigation to Setting Screen.
			Intent i = new Intent(this, SettingActivity.class);
			startActivityForResult(i, RESULT_SETTINGS);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// Function for button Sync.
	public void FunBtnSync() {
		try {
			// Check Internet Connection
			cd3 = new Connection(LoginActivity.this);
			isInternetPresent3 = cd3.isConnectingToInternet();
			if (isInternetPresent3) {
				new btnSyncTask().execute();
			} else {
				Toast.makeText(LoginActivity.this,
						"Please check your internet connection..",
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private String GetPrefSettingsByKey(String key) {
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		return sharedPrefs.getString(key, "");
	}

	// Sync All Details from server.
	private class btnSyncTask extends AsyncTask<String, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
		String StrMsg = null;

		protected void onPreExecute() {
			this.dialog.setMessage("Loading...");
			this.dialog.setCanceledOnTouchOutside(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... a) {
			try {

				String strUserName = edtUsername.getText().toString();
				String strPassword = edtPassword.getText().toString();
				Download ObjDL = new Download(LoginActivity.this, strUserName,
						strPassword);
				ObjDL.GetAllUsers();
				ObjDL.GetCompany();
				ObjDL.GetAllCustomers();
				ObjDL.GetAllCustomersLocations();
				ObjDL.GetAllGSTTypes();
				ObjDL.GetAllGroupPriceTables();
				ObjDL.GetAllPriceTables();
				ObjDL.GetAllProductGroups();
				ObjDL.GetAllProducts();
				ObjDL.GetAllUnitConversionByProducts();
				ObjDL.GetAllUnitofMeasures();
				ObjDL.GetSystemSettings();
				ObjDL.GetImage("SystemLogo");
				ObjDL.GetImage("PrintHeaderLogo");
				ObjDL.GetImage("PrintFooterLogo");
				ObjDL.GetMenu();
				ObjDL.GetMSTMultiTierDiscountOP();
				ObjDL.GetAllBrand();
				ObjDL.GetAllMade();
				ObjDL.GetAllModel();
				StrMsg = "Success";
			} catch (Exception ex) {
				StrMsg = ex.getMessage();
			}

			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				this.dialog = null;
			}
			try {
				if (StrMsg != null) {
					if (StrMsg.equals("Success")) {
						Toast.makeText(LoginActivity.this,
								"Data sync successfully!", Toast.LENGTH_LONG)
								.show();
						finish();
						startActivity(getIntent());

					} else {
						Toast.makeText(LoginActivity.this, StrMsg,
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(LoginActivity.this,
							"Please check the network connection!!!",
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

				ex.printStackTrace();

			}

		}

	}// Sync End

	public int CharToASCII(final char character) {
		return (int) character;
	}

	private void AlertDialog(String Message) {
		// TODO Auto-generated method stub
		_Alert = new AlertDialog.Builder(LoginActivity.this);
		_Alert.setTitle("Login");
		_Alert.setMessage(Message);
		_Alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Write your code here to invoke YES event
				dialog.dismiss();
			}
		});
		_Alert.show();

	}

}
